package top.zywork.wrapper;

import lombok.extern.slf4j.Slf4j;
import top.zywork.common.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * XssHttpServletRequestWrapper包装类<br/>
 *
 * 创建于2019-01-25<br/>
 *
 * @author 王振宇
 * @version 1.0
 */
@Slf4j
public class AppAuthHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private String postJsonStr;

    public String getPostJsonStr() {
        return postJsonStr;
    }

    public AppAuthHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            postJsonStr = IOUtils.getText(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            log.error("read post json str from request error: {}", e.getMessage());
        }

    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(postJsonStr.getBytes());
        return new ServletInputStream() {

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) { }
        };
    }
}